
import json
import urllib.request
import urllib.error


def http_multipart(context, request_url, info, file_data):
    boundary='-------------------------7df3069603d6'  
    data=[]

    for k,v in info.items():
        data.append('--%s' % boundary)
        data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
        data.append(v)

    for item in file_data:
        data.append('--%s' % boundary)
        # name字段决定Flask的request.files里面的关键字。
        data.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (item[0], item[1]))
        data.append('Content-Type: application/octet-stream\r\n')
        data.append(item[2])

    data.append('--%s--\r\n'%boundary)

    httpBody='\r\n'.join(data)  
    content_type = 'multipart/form-data; boundary=%s' % boundary

    req=urllib.request.Request(request_url, httpBody, {'Cookie':context.get('cookie')} )

    req.add_header( "Content-Type", content_type )

    try:
        response = urllib.request.urlopen( req )
        rsp = response.read().decode( 'utf-8' )
        # print the_page
        return rsp
        #return the_page
    except urllib.error.HTTPError as e:
        print(e.code)
        pass
    except urllib.error.URLError as e:
        print(str(e))
        pass
